package com.bdqn.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatisUtil
 *
 * @author LILIBO
 * @since 2024/6/25
 */
public class MyBatisUtil {

    private static final String resource = "mybatis-config.xml";

    private static SqlSessionFactory factory = null;

    /*
     * 类加载时
     */
    static {
        // 初始化SqlSessionFactory工厂
        initSqlSessionFactory();
    }

    /**
     * 初始化SqlSessionFactory工厂
     */
    public static void initSqlSessionFactory() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.fillInStackTrace();
        }
        factory = new SqlSessionFactoryBuilder().build(is);
    }

    /**
     * 获取SqlSession对象
     *
     * @return
     */
    public static SqlSession getSqlSession() {
        return factory.openSession(true); // 设置true表示自动提交，遇到分号(;)提交
    }

    /**
     * 关闭SqlSession对象
     *
     * @return
     */
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

}
